package com.example.stlink.activitys;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ZoomControls;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.example.stlink.R;
import com.example.stlink.configs.adapter.LocationPoiAdapter;
import com.example.stlink.configs.onRecyclerViewItemClickListener;
import com.example.stlink.model.constants.ModelFieldConstants;
import com.example.stlink.utils.MyLocationListener;

import java.util.ArrayList;
import java.util.List;

public class MapActivity extends AppCompatActivity {
    private MapView mMapView = null;
    private BaiduMap mBaiduMap = null;
    private LocationClient mLocationClient = null;
    BitmapDescriptor bitmap = null;

    private ImageView ivRelocation;
    private ImageButton abBtReturn;
    private AppCompatButton abBtSave;

    private MyLocationListener myLocationListener;
    private BDLocation nowLocation;

    private RecyclerView mRecyclerView;
    private LocationPoiAdapter adapter;
    private List<PoiInfo> mList;

    private Handler myLocationListenerHandler;
    private Handler locationPoiHandler;

    private onRecyclerViewItemClickListener recyclerViewItemClickListener;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        LocationClient.setAgreePrivacy(true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);

        initView();
    }


    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        mLocationClient.stop();
        mBaiduMap.setMyLocationEnabled(false);
        MyLocationListener.isFirstLocate = true;
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();
    }

    /**
     * 初始化地图相关
     */
    @SuppressLint("NotifyDataSetChanged")
    private void initView(){
        //获取布局相关控件
        mMapView = findViewById(R.id.b_map_view);
        ivRelocation = findViewById(R.id.iv_relocation);
        abBtReturn = findViewById(R.id.ab_bt_return);
        abBtSave = findViewById(R.id.ab_bt_save);
        bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.location);

        mRecyclerView= findViewById(R.id.rv_msg);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        locationPoiHandler = new Handler(msg -> {
            if(msg.arg1 == 1){
                adapter=new LocationPoiAdapter(MapActivity.this,mList);
                mRecyclerView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                adapter.setOnItemClickListener(recyclerViewItemClickListener);
            }
            return false;
        });

        myLocationListenerHandler = new Handler(msg -> {
            nowLocation = myLocationListener.getLocation();
            if(msg.arg1 == 200 && nowLocation != null){
                LatLng point = new LatLng(nowLocation.getLatitude(), nowLocation.getLongitude());
                System.out.println("reverseGeocoding: start!!!!!!!!!!!!");
                //单次定位结束，销毁定位
                System.out.println("mBaiduMap:closing................");
                mLocationClient.stop();
                //关闭定位图层
//                    mBaiduMap.setMyLocationEnabled(false);
                //开始地理反编码
                reverseGeocoding(point);
            }else{
                System.out.println("mLocationClient : " + mLocationClient.toString());
                System.out.println("nowLocation : " + nowLocation);
            }
            return false;
        });

        // 得到地图
        mBaiduMap = mMapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        //设置默认放大倍数
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().zoom(20).build()));
        mMapView.getMap().setMaxAndMinZoomLevel(21, 19);
        //定位初始化
        try {
            mLocationClient = new LocationClient(MapActivity.this);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 隐藏logo
        View child = mMapView.getChildAt(1);
        if ((child instanceof ImageView || child instanceof ZoomControls)){
            child.setVisibility(View.INVISIBLE);
        }
        //隐藏放大缩小控件
        mMapView.showZoomControls(false);

        //通过LocationClientOption设置LocationClient相关参数
        LocationClientOption locationClientOption = new LocationClientOption();
        // 可选，设置定位模式，默认高精度 LocationMode.Hight_Accuracy：高精度
        locationClientOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        locationClientOption.setOpenGps(true); // 打开gps
        locationClientOption.setCoorType("bd09ll"); // 设置坐标类型
        locationClientOption.setScanSpan(1000);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        // 可选，设置地址信息
        locationClientOption.setIsNeedAddress(true);
        locationClientOption.setIsEnableBeidouMode(true);
        //可选，设置是否需要地址描述
        locationClientOption.setIsNeedLocationDescribe(true);
        //设置locationClientOption
        mLocationClient.setLocOption(locationClientOption);

        //注册LocationListener监听器, 获取本地定位
        myLocationListener = new MyLocationListener(mMapView, mBaiduMap, myLocationListenerHandler);
        mLocationClient.registerLocationListener(myLocationListener);
        //开启地图定位图层
        mLocationClient.start();

        //设置其他监听事件
        setOtherListener();
    }


    /**
     * 地理反编码
     * @param point 经纬度
     */
    private void reverseGeocoding(LatLng point){
        //实例化一个地理编码查询对象
        GeoCoder geoCoder = GeoCoder.newInstance();
        //设置反地理编码位置坐标
        ReverseGeoCodeOption op = new ReverseGeoCodeOption();
        op.location(point);
        op.pageSize(1);
        //发起反地理编码请求(经纬度->地址信息)
        geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
            @Override
            public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
                if (geoCodeResult == null
                        || geoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
                    Toast.makeText(getApplicationContext(), "没有检测到结果", Toast.LENGTH_SHORT).show();
                }
            }
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
                if (reverseGeoCodeResult == null
                        || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
                    Toast.makeText(getApplicationContext(), "没有检测到结果", Toast.LENGTH_SHORT).show();
                } else {
                    System.out.println("reverseGeocoding: success!!!!!!!!!!!!");
                    reverseGeoCodeResult.getPoiList();
                    mList = (ArrayList<PoiInfo>) reverseGeoCodeResult.getPoiList();
                    System.out.println("mList : " + mList);
                    Message message = new Message();
                    message.arg1 = 1;
                    //发送消息，将反编码结果刷新到布局上
                    locationPoiHandler.sendMessage(message);
                }
            }
        });
        geoCoder.reverseGeoCode(op);
        // 释放实例
        geoCoder.destroy();
    }

    /**
     * 设置点击事件监听
     */
    private void setOtherListener(){
        //重定位
        ivRelocation.setOnClickListener(v -> {
            //点击重定位按钮，启动定位
            System.out.println("mBaiduMap:starting................");
            mLocationClient.start();
            //开启定位图层
//                mBaiduMap.setMyLocationEnabled(true);
//                BDLocation nowLocation = myLocationListener.getLocation();
//                LatLng ll = new LatLng(nowLocation.getLatitude(), nowLocation.getLongitude());
//                MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(ll);
//                mBaiduMap.animateMapStatus(msu);
        });
        abBtReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //保存
        abBtSave.setOnClickListener(v -> {
            nowLocation = myLocationListener.getLocation();
            String  ll = "(" + nowLocation.getLatitude() + "," + nowLocation.getLongitude() + ")";
            Intent intent = new Intent();
            Bundle bundle = getIntent().getExtras();
            bundle.putString(ModelFieldConstants.LOCATION, ll);
            intent.putExtras(bundle);
            setResult(100,intent);
            finish();
        });
        recyclerViewItemClickListener = new onRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(RecyclerView parent, View view, int position) {
                PoiInfo poiInfo = mList.get(position);
                //添加"Yes"按钮
                //添加取消
                AlertDialog alertDialog2 = new AlertDialog.Builder(MapActivity.this)
                        .setMessage("签到地点【" + poiInfo.name + "】")
                        .setPositiveButton("确定", (dialogInterface, i) -> {
                            Intent intent = new Intent();
                            Bundle bundle = getIntent().getExtras();
                            bundle.putString(ModelFieldConstants.LOCATION, poiInfo.name);
                            intent.putExtras(bundle);
                            setResult(100,intent);
                            finish();
                        })
                        .setNegativeButton("取消", (dialogInterface, i) -> {
                        })
                        .create();
                alertDialog2.show();
            }

            @Override
            public void onItemLongClick(RecyclerView parent, View view, int position) { }
        };

    }
}

